# coding = utf-8
import os

import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
#from PIL import Image
# from mahotas.features import surf
import tkinter as tk
from tkinter import filedialog
import re

root = tk.Tk()
root.geometry("500x500")
root.title("padding参数工具")

image = None
mask_out = None


def mask_mask_padding():
    paddingTop = 650
    paddingButtom = 100
    padding_v = padding_e.get()
    #padding_arr = padding_v.split(",")
    padding_arr = re.split(',|，',padding_v)
    if padding_arr[0] == '':
        padding_arr = []
    if len(padding_arr) == 1:
        paddingTop = int(padding_arr[0])
    elif len(padding_arr) == 2:
        paddingTop = int(padding_arr[0])
        paddingButtom = int(padding_arr[1])
    maskAll = np.zeros(image.shape[0:2], dtype="uint8")
    cv.rectangle(maskAll, (0, paddingTop), (image.shape[1], image.shape[0] - paddingButtom), 255, -1)

    gray = cv.cvtColor(image, cv.COLOR_RGB2GRAY)
    global mask_out
    mask_out = cv.bitwise_and(gray, maskAll)
    file_out = 'padding_out.jpg';
    cv.imwrite(file_out, mask_out)
    return file_out


def choose_image():
    src_FILEs = filedialog.askopenfilenames(initialdir="images/", title="选择图片",
                                          filetypes=(("JPEG files", "*.jpg"), ("PNG files", "*.png")))
    print(src_FILEs)
    # 导入资源
    global image
    if len(src_FILEs)>1:
        img1 = cv.imread(src_FILEs[0])
        img2 = cv.imread(src_FILEs[1])
        #image = cv.imread(src_FILE)  # r"D:\data\IMG_20230719_105059.jpg"
        image = cv.hconcat([img1, img2])
    else:
        image = cv.imread(src_FILEs[0])
    # image_show = cv.imdecode(np.fromfile(src_FILE, dtype=np.uint8), -1)
    # image_copy = np.copy(image_show)
    image_copy = cv.cvtColor(image, cv.COLOR_BGR2RGB)
    plt.imshow(image_copy)
    plt.show()  #最终显示


def do_image():
    out_file_path = mask_mask_padding()
    out_file_path_full = os.path.join(os.getcwd(),out_file_path)
    print(out_file_path_full)
    out_e.set(out_file_path_full)
    os.startfile(out_file_path_full)


button = tk.Button(root, text="选择首尾两张照片", command=choose_image)
button.pack(side="top", pady=50)

padding_label = tk.Label(root, text='padding')  # ,anchor='c').grid(row=0,column=0)
padding_label.pack(side="top")
padding_e = tk.StringVar()
padding = tk.Entry(root, width=20, textvariable=padding_e)  # .grid(row=0,column=1)
padding.pack(side="top")
# padding_e.set('输入padding参数，,分隔上下边距的像素')

button_do = tk.Button(root, text="查看效果", command=do_image)
button_do.pack(side="top", pady=50)

out_e = tk.StringVar()
out_label = tk.Label(root, text='输处目录:', textvariable=out_e)
out_label.pack(side="bottom")

root.mainloop()
